from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.firefox.service import Service

from phone import *
from selenium.webdriver.common.proxy import Proxy, ProxyType



def _parse_cookies(driver):
    cookies = driver.get_cookies()
    logger.info(f"cookies: {cookies}")
    if cookies:
        new_cookie = {}
        for cookie in cookies:
            new_cookie[cookie['name']] = cookie['value']
        return new_cookie


def get_proxy():
    url = "http://http.tiqu.letecs.com/getip3?num=1&type=1&pro=&city=0&yys=0&port=1&pack=29238&ts=0&ys=0&cs=0&lb=1&sb=0&pb=4&mr=1&regions=&tl=2"
    response = requests.get(url, timeout=3)
    proxy_str = response.text.replace("\r\n", "")
    logger.info(f"proxy: {proxy_str}")
    return proxy_str


def fetch_cookie(token, phone):
    service = Service(executable_path='./geckodriver.exe')
    options = webdriver.FirefoxOptions()
    # options.add_argument('--headless')
    driver = webdriver.Firefox(service=service, options=options)
    driver.implicitly_wait(3)
    driver.get('https://www.qcc.com/')
    driver.find_element(By.XPATH, "/html/body/div[1]/div[1]/div/div[1]/nav[2]/ul/li[16]/a").click()
    driver.find_element(By.XPATH, "/html/body/div[2]/div/div/div/div[3]/img").click()
    phone = get_phone(token, phone)
    driver.find_element(By.XPATH, "/html/body/div[2]/div/div/div/div[1]/div[2]/form/div[1]/input").send_keys(phone)
    time.sleep(2)
    driver.find_element(By.XPATH, "/html/body/div[2]/div/div/div/div[1]/div[2]/form/div[3]/div").click()
    time.sleep(8)
    code = get_msg(token, phone)
    if code:
        driver.find_element(By.XPATH, "/html/body/div[2]/div/div/div/div[1]/div[2]/form/div[3]/input").send_keys(code)
        driver.find_element(By.XPATH, "/html/body/div[2]/div/div/div/div[1]/div[2]/form/div[4]/button").click()
        return _parse_cookies(driver)
    else:
        logger.info("未获取到验证码")
        driver.quit()
